package com.deuwise.job.customquartz;


import com.deuwise.common.utils.RSAUtils;
import com.deuwise.job.customquartz.base.JobRun;
import com.deuwise.system.entity.KeyPairDo;
import com.deuwise.system.service.KeyPairDoService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JobKeyPairLog implements Job,JobRun {

    @Autowired
    private KeyPairDoService keyPairDoService;
    /** 公钥 */
    private static final String PUBLIC_KEY = "RSAPublicKey";
    /** 私钥 */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    @Override
    public void run() {
        System.out.println("JobKeyPairLog：执行RSA秘钥重建=======================");
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Map<Integer, String> keyMap = RSAUtils.genKeyPair();
        /*入库操作*/
        boolean isSuccess = insertKeyPairDo(keyMap);
    }

    /**
     * 秘钥入库
     * @param keyMap
     * @return
     */
    public boolean insertKeyPairDo(Map<Integer, String> keyMap) {
        List<KeyPairDo> list = new ArrayList<KeyPairDo>();
        boolean isSuccess = false;
        try{
            for(Map.Entry<Integer, String> entry : keyMap.entrySet()){
                Integer mapKey = entry.getKey();
                String mapValue = entry.getValue();
                KeyPairDo keyPairDo = new KeyPairDo();
                if(0 == mapKey){
                    // 公钥
                    keyPairDo.setKey(PUBLIC_KEY);
                    keyPairDo.setRemark("公钥");
                }else {
                    keyPairDo.setKey(PRIVATE_KEY);
                    keyPairDo.setRemark("私钥");
                }
                keyPairDo.setValue(mapValue);
                list.add(keyPairDo);
            }
            isSuccess = keyPairDoService.insertBatch(list);
        }catch (Exception e){
            e.printStackTrace();
        }
        return isSuccess;
    }
}
